<template>
  <div id="content-manage" ref="workBox">
    <h1 class="title">内容管理</h1>
    <div class="main-cont">
      <v-toolbar @click="handleToolClick"></v-toolbar>
    <div class="table-cont mt10">
      <el-table :data="tableData" :height="height" v-loading="loading">
        <el-table-column prop="Id" label="序号"></el-table-column>
        <el-table-column label="封面图片">
          <template slot-scope="scope">
            <img :src="scope.row.ImageUrl" />
          </template>
        </el-table-column>
        <el-table-column prop="Title" label="标题"></el-table-column>
        <el-table-column prop="SubTitle" label="副标题"></el-table-column>
        <el-table-column label="创建日期">
          <template slot-scope="scope">
            {{new Date(scope.row.Created*1000).getFullYear()+'/'+new Date(scope.row.Created*1000).getMonth()+'/'+new Date(scope.row.Created*1000).getDate()}}
          </template>
        </el-table-column>
        <el-table-column label="设置">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="modifyArticle(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="delArticle(scope.row.Id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    </div>
    <v-dialog
      :title="editMode === 'ADD' ? '新建内容':'修改内容'"
      :isVisible="dialogFormVisible"
      @close="closeDialog">
      <template slot="dialog-cont">
        <el-form :model="form" :rules="rules" ref="form" class="dialog-main dialogForm">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="标题" prop="Title">
                <el-input v-model="form.Title" placeholder="请输入标题"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="副标题" prop="SubTitle">
                <el-input v-model="form.SubTitle" placeholder="请输入副标题"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="内容类别" prop="ArticleClass">
                <el-select v-model="form.ArticleClass" placeholder="请选择内容类别" popper-class="zIndex-popper" @change="handleArtClassChange">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="内容分类" prop="ClassifyList">
                <el-checkbox-group v-model="form.ClassifyList">
                  <el-checkbox v-for="item in ClassifyListOpts" :label="item.Id" :key="item.Id">{{item.Name}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24" v-if="form.ArticleClass === 'AC1'">
              <el-form-item label="正文" style="margin-bottom:37px" prop="Body">
                <quillEditor v-model="form.Body" :options = "editorOption"></quillEditor>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="BeginDate">
                <el-date-picker
                  v-model="form.BeginDate"
                  type="date"
                  placeholder="请选择开始日期"
                  popper-class="zIndex-popper"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="EndDate">
                <el-date-picker
                  v-model="form.EndDate"
                  type="date"
                  placeholder="请选择结束日期"
                  popper-class="zIndex-popper"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="BeginTime">
                <el-time-select
                  v-model="form.BeginTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:01',
                    end: '24:00'
                  }"
                  placeholder="请选择开始时间"
                  popper-class="zIndex-popper"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="EndTime">
                <el-time-select
                  v-model="form.EndTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:01',
                    end: '24:00'
                  }"
                  placeholder="请选择结束时间"
                  popper-class="zIndex-popper"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="封面图片" prop="ImageUrl">
                <v-upload title="选择封面图片" :picUrl="form.ImageUrl" :size="{width:150, height:150}" @change="handlePicChange"></v-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template slot="dialog-btns">
        <div class="form-buttons">
          <el-button @click="resetForm" size="mini">重置</el-button>
          <el-button @click="closeDialog" size="mini">关闭</el-button>
          <el-button type="primary" @click="submitForm" size="mini">确定</el-button>
        </div>
      </template>
    </v-dialog>
  </div>
</template>
<script>
  import VToolbar from '../../comm/iToolbar/iToolbar'
  import VDialog from '../../comm/iDialog/iDialog'
  import VUpload from '../../comm/iUpload/iUpload'
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/ajax'
  import { nextPage } from '../../../../assets/js'
  import { quillEditor } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  export default {
    components: {
      VToolbar,
      VDialog,
      VUpload,
      quillEditor
    },
    data () {
      let checkDate = (rule, value, callback) => {
        let form = this.form
        if (form.BeginDate && form.EndDate) {
          if (form.BeginDate > form.EndDate) {
            callback(new Error('开始日期不能大于结束日期'))
          }
          callback()
        }
        callback()
      }
      let checkTime = (rule, value, callback) => {
        let form = this.form
        if (form.EndTime && form.BeginTime) {
          if (form.BeginTime > form.EndTime) {
            callback(new Error('开始时间不能大于结束时间'))
          }
          callback()
        }
        callback()
      }
      return {
        rules: {
          Title: [
            { required: true, message: '请填写内容标题', trigger: 'blur' }
          ],
          ImageUrl: [
            { required: true, message: '请选择封面图片', trigger: 'change' }
          ],
          Body: [
            { required: true, message: '请填写内容内容', trigger: 'blur' }
          ],
          ClassifyList: [
            { required: true, message: '请选择内容分类', trigger: 'channge' }
          ],
          ArticleClass: [
            { required: true, message: '请选择内容类别', trigger: 'blur' }
          ],
          BeginDate: [
            { validator: checkDate }
          ],
          EndDate: [
            { validator: checkDate }
          ],
          BeginTime: [
            { validator: checkDate }
          ],
          EndTime: [
            { validator: checkTime }
          ]
        },
        tableData: [],
        ImgTableData: [],
        height: null,
        url: '',
        options: [
          { label: '手动编辑', value: 'AC1' }
        ],
        ClassifyListOpts: [],
        form: {
          Title: '',
          SubTitle: '',
          ArticleClass: '',
          ImageUrl: '',
          Body: '',
          BeginDate: '',
          EndDate: '',
          BeginTime: '',
          EndTime: '',
          ClassifyList: []
        },
        formData: {},
        dialogFormVisible: false,
        editMode: 'ADD',
        msg: '新增成功',
        ifQuill: false,
        editorOption: {},
        loading: true
      }
    },
    methods: {
      // 工具栏操作
      handleToolClick (opt) {
        switch (opt) {
          case 'add':
            this.addArticle()
            break
          default:
            break
        }
      },
      // 获取内容列表
      getArticleList () {
        ajax.get(api.QUERY_ARTICLES).then(res => {
          if (res && res.length > 0) {
            this.tableData = res
          } else {
            this.tableData = []
          }
          this.loading = false
        }).catch(() => {})
      },
      // 内容类别下拉框触发事件
      handleArtClassChange () {
        if (this.form.ArticleClass === 'AC1') {
          this.ifQuill = true
        }
      },
      // 查询内容分类
      getClassifyList () {
        let getData = {
          dictionaryid: 'ArticleClassify'
        }
        ajax.get(api.QUERY_DICTIONARY_DETAILS, getData).then(res => {
          if (res && res.length > 0) {
            this.ClassifyListOpts = res
          } else {
            this.$confirm('暂无内容分类，部分操作将不能实现，是否前去添加内容分类？', '温馨提示', {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
              type: 'warning'
            }).then(res => {
              nextPage('/home/cateSetting')
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
          }
        })
      },
      // 获取内容详情
      getArticleDetails (id) {
        ajax.get(api.QUERY_ARTICLE_DETAIL, {id: id}).then(res => {
          this.form = res
          this.formData = JSON.parse(JSON.stringify(res))
          if (this.form.ClassifyList === undefined) {
            this.form.ClassifyList = []
          } else {
            this.changeClassifyList('rec')
          }
        })
      },
      // 新建/修改内容
      addArticle (id) {
        this.editMode = 'ADD'
        this.dialogFormVisible = true
      },
      // 修改内容
      modifyArticle (data) {
        this.getArticleDetails(data.Id)
        this.handleArtClassChange()
        this.editMode = 'EDIT'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.form.resetFields()
        })
      },
      // 选择封面图片处理
      handlePicChange (data) {
        this.form.ImageUrl = data.url
      },
      // 关闭弹窗
      closeDialog () {
        this.initForm('form')
        this.dialogFormVisible = false
      },
      // 新建/修改内容 确定按钮
      submitForm () {
        let port = api.ADD_ARTICLECREATE
        if (this.editMode === 'EDIT') {
          this.msg = '修改成功'
          port = api.ADD_ARTICLE_UPDATE
        }
        this.changeClassifyList('send')
        // 校验
        this.$refs['form'].validate((valid) => {
          if (valid) {
            ajax.post(port, this.form).then(res => {
              if (res.Code === 0) {
                this.$message({// type: 'success',
                  type: 'success',
                  message: this.msg
                })
              }
              this.closeDialog()
              this.getArticleList()
            })
          } else {
            return false
          }
        })
      },
      // 初始化表单
      initForm (formName) {
        this.$refs[formName].resetFields()
        this.form = {
          Title: '',
          SubTitle: '',
          ArticleClass: '',
          ImageUrl: '',
          Body: '',
          BeginDate: '',
          EndDate: '',
          BeginTime: '',
          EndTime: '',
          ClassifyList: []
        }
      },
      // 重置
      resetForm () {
        this.initForm('form')
        if (this.editMode === 'EDIT') {
          this.form = { ...this.formData }
        }
      },
      // 删除内容
      delArticle (id) {
        this.$confirm('确定要删除该内容吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          ajax.get(api.DELETE_ARTICLE, {id: id}).then(res => {
            if (res.Code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            }
            this.getArticleList()
          }).catch(() => {})
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 内容分类 传值格式转换
      changeClassifyList (e) {
        let arr = this.form.ClassifyList
        let arrc = []
        if (e === 'rec') {
          for (let i = 0; i < arr.length; i++) {
            arrc.push(arr[i].Id)
          }
        } else {
          for (let i = 0; i < arr.length; i++) {
            arrc.push({Id: arr[i]})
          }
        }
        this.form.ClassifyList = arrc
      }
    },
    created () {
      this.$nextTick(() => {
        this.height = this.$refs.workBox.offsetHeight - 138
        this.getArticleList()
        this.getClassifyList()
      })
    }
  }
</script>
<style lang="stylus">
  #content-manage
    height 100%
    overflow hidden
    .checked
      display block
      margin-left 15px
      width 32px
      height 32px
      background url('') no-repeat center center
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .mt10
      margin-top 10px
    .main-cont
      padding 10px 0 0 10px
    .table-cont
      img
        height:30px;
        max-width:50px
  .ql-toolbar.ql-snow .ql-formats
    line-height 24px
  .ql-editor
    height:300px
    overflow-y scroll
</style>
